import  './Spell.css'
import React , {useState,useEffect, useRef} from 'react'
import {_MAX_TARGET,_TARGET_CONFIG,_DICTIONARY} from '../constant/index'

import Particles from "react-tsparticles";
import options from '../constant/configData'

export default function Spell() {
  //初始化数据
  const wordsPool = _DICTIONARY.concat([]).sort(()=>0.5-Math.random())
  let targetArr = wordsPool.splice(0,_MAX_TARGET).map((item,index)=>{
    return{
      txt:item,
      left:Math.floor((Math.random()+index)*340/_MAX_TARGET),
      top:Math.floor((Math.random() - 1)*_MAX_TARGET +1)*60,
    }
  })
  targetArr = targetArr.map((item,index)=>({
    ...item,
    direction:item.left<175?1:-1
  }))
  let [input,setInput] = useState('')
  let [fix,setFix] = useState(false)
  const [state,setState] = useState({
      targetArr, // 存放当前目标
      wordsPool,//剩余单词库
      score: 0,//分数
      gameOver: false,
      color:['Blue','Pink','Aqua','FloralWhite','Chartreuse','BlueViolet']
  })

  const down = ()=>{
    let newArr = [...state.targetArr]
    let timer = setInterval(()=>{
      newArr = newArr.map(item=>{
        let newDire = item.direction
        if(item.left<0||item.left>350)newDire = item.direction*-1
       return{
         ...item,
         top:item.top+_TARGET_CONFIG.speed,
         left:item.left+newDire,
         direction:newDire
        //  direction:(item.left<0||item.left>350 )?item.direction*(-1):item.direction
       }
     })
     let isBottom = newArr.find(item=>item.top>=600-60) 
     if(isBottom){
       clearInterval(timer)
       setState((state)=>{
         return {
         ...state,
         gameOver:true
         }
       })
     }
     setState((state)=>{
      state.score>localStorage.getItem('_HIGHEST_RECORD')&&
      localStorage.setItem('_HIGHEST_RECORD',state.score)
       return {
        ...state,
        targetArr:newArr
        }
     })
     },17)
  }

  
   



  useEffect(()=>{
    console.log('useEffect');
    down()
  },[])
  
  
  //当前锁定单词在目标数组索引
  let [currentIndex,setCurrentIndex] = useState(-1)
    const inputChange = (e) => {
    if(currentIndex===-1){
      //没有目标索引 寻找输入首字母相同的单词数组并求top值大的索引 并赋给他
      let matchObj = state.targetArr.filter(item=>item.txt[0]===e.target.value&&item.top>0)
      if(matchObj.length){
        matchObj = matchObj.reduce((pre,cur)=>{
          return cur.top>pre.top?cur:pre
        })
        let tempIndex = state.targetArr.indexOf(matchObj)
        console.log(tempIndex);
        setCurrentIndex(tempIndex)
        setInput(e.target.value)
      }else{
        return
      }
    }else if(new RegExp(e.target.value).test(state.targetArr[currentIndex].txt)){
      //单词包含输入框的单词 就setInput 当单词与输入框单词相同时就清除目标并添加下一个单词
      setInput(e.target.value)
      e.target.value===state.targetArr[currentIndex].txt &&clearAddTarget(currentIndex)
    }
  }
  //清除拼写完的目标放回单词库 并随机添加进一个新的
  const clearAddTarget = (index) => {
    let {targetArr,wordsPool,score} = state
    wordsPool.push(targetArr[index].txt)
    targetArr[index] = {
      txt:wordsPool[Math.floor(Math.random()*(wordsPool.length-1))],
      left:Math.floor(Math.random()*340),
      top:Math.floor(Math.random()*1),
      direction:Math.random()>0.5?1:-1
    }
    //分数加一
     score++
    setState({
      ...state,
      wordsPool,
      targetArr,
      score
    })
    //单词索引 输入框清除
    setCurrentIndex(-1)
    setInput('')
  }

  let [speed,setSpeed] = useState(0)
  //监听分数并逐渐加快速度
  useEffect(()=>{
    if((state.score+1)%(_MAX_TARGET+1)===0){
      _TARGET_CONFIG.speed += 0.1
      setSpeed(_TARGET_CONFIG.speed)
    }
  },[state.score])


  const audio = useRef(null)
  let [isPaly,setIsPlay] = useState(false)
  const palyAudio = () => {
    audio.current.volume = 0.3
    if(isPaly){
    audio.current.pause()
    }else{
    audio.current.play()
    }
    setIsPlay(!isPaly)
  }

  

  return (
    <div>
     {/* 粒子背景 */}
    <Particles id="tsparticles"
     options={options} /> 

     {/* 目标单词渲染 */}
     <div style={{width:'100%',height:'600px',position:'absolute',overflow:'hidden'}}>
       {state.targetArr.map((item,index)=>(
         <div key={index} className={`target ${currentIndex===index?'aim':''}`} style={{left:item.left+'px',top:item.top+'px',color:state.color[index]}}>
           <div style={{marginTop:'40px',minWidth:'40px',textAlign:'center'}}>{item.txt.split('').map((key,i)=>(
             <span style={{color:currentIndex===index&&key===input[i]?'yellow':''}} key={i}>{key}</span>
           ))}</div>
         </div>
       ))}
     </div>

     {/* 分数和输入框 */}
     <div className='contentBox screenClass'>
        <div>
          <div >分数:{state.score}</div>
          <div onClick={()=>{setFix((value)=>{
            value&& window.location.reload()
            return !value
          })}}
           style={{fontSize:'35px',marginTop:'-10px',zIndex:999,cursor:'pointer'}}>{fix?'×':'⚙'}</div>
        </div>
        <span className='inputBox'>
          <input style={{}} autoFocus="autoFocus" type='text' className='inputClass' value={input} onChange={(e)=>inputChange(e)}></input>
        </span>
     </div>
     
     {/* 设置 */}
     <div className='contentBox'>
        <div onClick={()=>window.location.reload()} className='overClass' style={{display:state.gameOver?'inline-block':'none'}}>
          <div>Game Over:{speed?.toFixed(1)+'-'+state.score}</div>
          <div style={{textAlign:'center'}}>再来一局</div>
        </div>
        <div className='menuClass' style={{display:fix?'flex':'none'}}>
          <span onClick={()=>palyAudio()}>声音:{isPaly?'✅':'❎'}</span>
          <span>速度:<input type='number' min="0.3" max="5" step="0.1" defaultValue={_TARGET_CONFIG.speed} onBlur={(e)=>{
            localStorage.setItem('speed',e.target.value)
          }}></input>
          </span>
          <span>数量:<input type='number' min="1" max="6" step="1" defaultValue={_MAX_TARGET} onBlur={(e)=>{
            localStorage.setItem('_MAX_TARGET',e.target.value)
          }}></input>
          </span>
          <span>词库:<input type='text' defaultValue='' placeholder='请用,隔开' onBlur={(e)=>{
            localStorage.setItem('_DICTIONARY',e.target.value)
          }}></input>
          </span>
          <span>最高纪录:{localStorage.getItem('_HIGHEST_RECORD')||0}</span>
          <span>Tips:失焦提交</span>
        </div>
     </div>
     
     {/* 声音*/}
      <audio ref={audio} hidden={true} loop controls>
        <source src={require('../assets/bgm.mp3')} type="audio/mpeg" />
      </audio>
    </div>
  )
}